package com.android.clinic.app.utils;

import android.support.annotation.NonNull;

import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.Days;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by cheng on 2018/3/26.
 */
public class TimeUtils {

    /**
     * 仿微信日期格式输出
     * @param msgTimeMillis
     * @return
     */
    public static String getChatFormatTime(long msgTimeMillis) {
        DateTime nowTime = new DateTime();
        DateTime msgTime = new DateTime(msgTimeMillis);
        int days = Math.abs(Days.daysBetween(msgTime, nowTime).getDays());
        if (days < 1) {
            //1:40
            return getTime(msgTime);
        } else if (days == 1) {
            //昨天
            return "昨天 " + getTime(msgTime);
        } else if (days <= 7) {
            //星期
            switch (msgTime.getDayOfWeek()) {
                case DateTimeConstants.SUNDAY:
                    return "星期日 " + getTime(msgTime);
                case DateTimeConstants.MONDAY:
                    return "星期一 " + getTime(msgTime);
                case DateTimeConstants.TUESDAY:
                    return "星期二 " + getTime(msgTime);
                case DateTimeConstants.WEDNESDAY:
                    return "星期三 " + getTime(msgTime);
                case DateTimeConstants.THURSDAY:
                    return "星期四 " + getTime(msgTime);
                case DateTimeConstants.FRIDAY:
                    return "星期五 " + getTime(msgTime);
                case DateTimeConstants.SATURDAY:
                    return "星期六 " + getTime(msgTime);
            }
            return "";
        } else {
            //12月22日
            return msgTime.toString("MM月dd日 " + getTime(msgTime));
        }
    }

    @NonNull
    private static String getTime(DateTime msgTime) {
        return msgTime.toString("HH:mm");
    }

    public static Integer transForMilliSecond(String dateStr, String format) {
        Date date = formatDate(dateStr, format);
        return date == null ? null : transForMilliSecond(date);
    }

    public static Integer transForMilliSecond(Date date) {
        if (date == null) return null;
        return (int) (date.getTime() / 1000);
    }

    public static Date formatDate(String dateStr, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date result = null;
        try {
            result = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

}
